<template>
    <div class="searchBar">
        <el-form :inline="true" :model="searchUserForm" class="demo-form-inline">
            <el-form-item label="用户编号">
                <el-input v-model="searchUserForm.userNum" placeholder="用户编号" style="width: 100px;" />
            </el-form-item>
            <el-form-item label="姓名">
                <el-input v-model="searchUserForm.username" placeholder="姓名" style="width: 100px;" />
            </el-form-item>
            <el-form-item label="角色">
                <el-select v-model="searchUserForm.userrole" clearable placeholder="角色" style="width: 100px;">
                    <el-option v-for="(item, index) in roles" :key="index" :label="item.roleName"
                        :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSubmit">查询</el-button>
            </el-form-item>
            <el-form-item>
                <!-- <el-button type="success" @click="onAddItem">新增</el-button> -->
                <!-- Form -->
                <el-button type="success" @click="dialogVisible = true">新增</el-button>
                <el-dialog v-model="dialogVisible" title="新增" width="30%" destroy-on-close center draggable>
                    <el-form ref="addFormRef" :model="addForm" :label-position="left" :rules="rules" label-width="120px"
                        class="demo-addForm">
                        <el-form-item label="用户编号：" :label-width="formLabelWidth" prop="userNum">
                            <el-input v-model="addForm.userNum" autocomplete="off" />
                        </el-form-item>
                        <el-form-item label="姓名：" :label-width="formLabelWidth" prop="username">
                            <el-input v-model="addForm.username" autocomplete="off" />
                        </el-form-item>
                        <el-form-item label="性别：" :label-width="formLabelWidth" prop="sex">
                            <el-select v-model="addForm.sex" placeholder="请选择性别">
                                <el-option label="男" value="1" />
                                <el-option label="女" value="0" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="角色：" :label-width="formLabelWidth" prop="userrole">
                            <el-select v-model="addForm.userrole" placeholder="请选择角色" autocomplete="off">
                                <el-option v-for="(item, index) in roles" :key="index" :label="item.roleName"
                                    :value="item.id" />
                            </el-select>
                        </el-form-item>
                        <el-alert title="初始密码为：123456" type="info" center show-icon />
                    </el-form>
                    <template>
                        <el-dialog v-model="innerVisible" width="30%" :title="msg" append-to-body />
                    </template>
                    <template #footer>
                        <span class="dialog-footer">
                            <el-button @click="dialogVisible = false">取消</el-button>
                            <el-button type="primary" @click="onAddItem(addFormRef)">
                                确定
                            </el-button>
                        </span>
                    </template>
                </el-dialog>
            </el-form-item>
        </el-form>
    </div>
    <div>
        <el-table :data="tableData.slice((currentPage - 1) * pagesize, currentPage * pagesize)" style="width: 100%"
            max-height="250">
            <el-table-column type="index" label="序号" width="80" />
            <el-table-column prop="userNum" label="用户编号" width="150" />
            <el-table-column prop="userName" label="姓名" width="120" />
            <el-table-column prop="sex" label="性别" width="120">
                <template #default="scope">
                    <span v-if="scope.row.sex == 1">男</span>
                    <span v-if="scope.row.sex == 0">女</span>
                </template>
            </el-table-column>
            <el-table-column prop="roleInfo.roleName" label="角色" width="120" />
            <el-table-column prop="address" label="Address" width="600" />
            <el-table-column prop="zip" label="Zip" width="120" />
            <el-table-column fixed="right" label="操作" width="300">
                <template #default="scope">
                    <el-button  type="primary" size="small" @click.prevent="updateUserFun(scope.$index)">
                        修改
                    </el-button>
                    <el-button  type="primary" size="small" @click.prevent="deleteRow(scope.$index)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="currentPage" :page-size="pagesize" layout="prev, pager, next, jumper"
            :total="tableData.length" v-if="(tableData.length != 0)">
        </el-pagination>
    </div>
    <updateUser :updateUserShow="updateUserShow" :userInfo="updateUserVal" :roles="roles"
        @closeUpdateUser="closeUpdateUser" @updateUserComplete="onSubmit"  />
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { getUserAllRoles } from '@/api/users'
import { UserModule } from '@/store/modules/user'
import { getUsers, addUser, deleteUser } from '@/api/users'
import type { FormInstance } from 'element-plus'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import type { Action } from 'element-plus'
import { left, right } from '@popperjs/core';
import updateUser from './components/updateUser.vue'

const searchUserForm = reactive({
    userNum: '',
    username: '',
    userrole: ''
})


const tableData = ref([])

const loading = ref(false);

//查询
const onSubmit = async() => {
    loading.value = true;
    try {
        const seachUsers:any =await getUsers(searchUserForm);
            // console.log(seachUsers.data.seachResult.users)
            // console.log(seachUsers.data.pageCount)
            tableData.value = seachUsers.data.seachResult.users;
            loading.value = false       
        // UserModule.GetUser(searchUserForm).then((res) => {
        //     tableData.value = res
        //     console.log(res);
            
        // })

    } catch (error) {
        searchUserForm.userNum = ''
        searchUserForm.username = ''
        searchUserForm.userrole = ''
        loading.value = false;
        console.log(error);
        ElMessage.error("搜索用户信息失败失败！！！")
    }
}

//获取角色
let roles: any = ref([]);
onMounted(async () => {
    roles.value = (await getUserAllRoles()).data.roles
    console.log("roles", roles)
})

const innerVisible = ref(false)
const dialogVisible = ref(false)
const formLabelWidth = '140px'
const addForm = reactive({
    userNum: '',
    username: '',
    userrole: '',
    sex: ''
})


//分页
const pagesize = ref(2)//每页多少个
const handleSizeChange = (size: any) => {
    // console.log(size);     
    pagesize.value = size;
    // console.log(pagesize.value); //每页下拉显示数据
}

const currentPage = ref(1)//默认第几页
const handleCurrentChange = (current: any) => {
    // console.log(current); 
    currentPage.value = current
    // console.log(currentPage.value); //点击第几页
}


// const updateRow = (index: number) => {
//     let data = tableData.value[pagesize.value * (currentPage.value - 1) + index]
//     console.log(data);
// }

//编辑用户信息
const updateUserShow = ref(false)
const closeUpdateUser = (v: boolean) => {
    // console.log(v)
    updateUserShow.value = false;
    onSubmit()
}
const updateUserVal = ref()
const updateUserFun = (index: number) => {
    let userInfo = tableData.value[pagesize.value * (currentPage.value - 1) + index]
    console.log("userInfo", userInfo)
    updateUserVal.value = userInfo;
    updateUserShow.value = true;
}

//删除
const deleteRow = (index: number) => {
    // tableData.value.splice(pagesize.value * (currentPage.value - 1) + index, 1)
    let data = tableData.value[pagesize.value * (currentPage.value - 1) + index]
    console.log(data.userNum);
    // loading.value = true;
    ElMessageBox.confirm(
        '确定要删除 ' + data.userName + '  这个用户吗?',
        '警告',
        {
            confirmButtonText: '确定删除',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(async () => {
        const loading = ElLoading.service({
            lock: true,
            text: 'Loading',
            background: 'rgba(0, 0, 0, 0.7)',
        })
        try {
            const deleteResult: any = await deleteUser(data.userNum);
            if (deleteResult.success) {
                ElMessage({
                    type: 'info',
                    message: deleteResult.info.msg,
                })
            } else {
                ElMessage({
                    type: 'warning',
                    message: deleteResult.info.msg,
                })
            }
            loading.close()
            onSubmit()
        } catch (error) {
            loading.close()
            console.log(error)
        }
    }).catch((error) => {
        console.log(error)
    })


}


const addFormRef = ref(null)

const checkUserno = (rule: any, value: any, callback: any) => {
    if (!value) {
        callback(new Error('请输入用户编号'))
    } else {
        callback()
    }
}

const checkUsername = (rule: any, value: any, callback: any) => {
    if (!value) {
        callback(new Error('请输入姓名'))
    } else {
        callback()
    }
}

const checkSex = (rule: any, value: any, callback: any) => {
    if (!value) {
        callback(new Error('请选择性别'))
    } else {
        callback()
    }
}

const checkUserrole = (rule: any, value: any, callback: any) => {
    if (!value) {
        callback(new Error('请选择角色'))
    } else {
        callback()
    }
}

const rules = reactive({
    userNum: [{ validator: checkUserno, trigger: 'blur' }],
    username: [{ validator: checkUsername, trigger: 'blur' }],
    userrole: [{ validator: checkUserrole, trigger: 'blur' }],
    sex: [{ validator: checkSex, trigger: 'blur' }],
})

const ruleFormRef = ref<FormInstance>()

const msg = ref(null)

//添加用户
const onAddItem = (formEl: FormInstance | undefined) => {
    console.log(addForm.userNum);
    console.log(addForm.username);
    console.log(addForm.userrole);
    if (!formEl) return
    formEl.validate(async (valid: boolean) => {
        if (valid) {
            try {
                const addResult: any = await addUser(addForm);
                if (addResult.success) {
                    dialogVisible.value = false
                    ElMessage({
                        type: 'info',
                        message: addResult.info.msg,
                    })
                } else {
                    dialogVisible.value = false
                    ElMessage({
                        type: 'warning',
                        message: addResult.info.msg,
                    })
                }  
                addForm.userNum = ''
                addForm.username = ''
                addForm.userrole = ''
                addForm.sex = ''
                onSubmit()
            } catch (error) {
                addForm.userNum = ''
                addForm.username = ''
                addForm.userrole = ''
                addForm.sex = ''
            }
            loading.value = false;
            dialogVisible.value = false
        } else {
            console.log('表单没填全')
            return false
        }
    })
}
</script>

<style scoped>
.searchBar {
    margin-top: 20px;
    margin-bottom: 20px;
}

.el-alert {
    margin: 20px 0 0;
}

.el-alert:first-child {
    margin: 0;
}
</style>